package org.watchrecords;

import org.apache.wicket.Component;
import org.apache.wicket.Session;
import org.apache.wicket.authorization.Action;
import org.apache.wicket.authorization.IAuthorizationStrategy;
import org.watchrecords.annotations.ActionPermission;
import org.watchrecords.annotations.ActionPermissions;
import org.watchrecords.annotations.InstantiationPermission;

public class PermissionAuthorizationStrategy implements IAuthorizationStrategy {

    @Override
    public boolean isActionAuthorized(Component component, Action action) {
        ActionPermission[] rules = null;
        
        if (component.getClass().isAnnotationPresent(ActionPermission.class)) {
            rules = new ActionPermission[] { component.getClass().getAnnotation(ActionPermission.class) };
        }
        else if (component.getClass().isAnnotationPresent(ActionPermissions.class)) {
            rules = component.getClass().getAnnotation(ActionPermissions.class).value();
        }
        
        if (rules == null) {
            return true;
        }

        WatchRecordsSession session = (WatchRecordsSession) Session.get();
        
        for (ActionPermission rule: rules) {
            if(session.haveAnyPermission(rule.permissions()) && rule.action().equals(action.getName())) {
                return true;
            }
        }
        
        return false;
    }

    @Override
    public <T extends Component> boolean isInstantiationAuthorized(Class<T> klass) {
        WatchRecordsSession session = (WatchRecordsSession) Session.get();
        InstantiationPermission rule = klass.getAnnotation(InstantiationPermission.class);
        
        if (rule != null) {
            return session.haveAnyPermission(rule.value());
        }
        
        return true;
    }

}
